﻿using UnityEngine;
using System.Collections;
using System.Runtime.CompilerServices;
using DG.Tweening;

public class Enemy : MonoBehaviour
{
    private Vector2 targetPos;
    private Rigidbody2D rd2D;
    private BoxCollider2D collider;
    private Transform playerTran;
    private Animator animator;
    public int lossFood=10;

    void Start()
    {
        targetPos = transform.position;
        rd2D = GetComponent<Rigidbody2D>();
        collider = GetComponent<BoxCollider2D>();
        playerTran = GameObject.FindGameObjectWithTag("Player").transform;
       animator = GetComponent<Animator>();
        GameManager.Instance.enemyList.Add(this);
    }

    public void EnemyMove()
    {
        Vector2 offset = transform.position - playerTran.position;
        float x = 0, y = 0;
        if (offset.magnitude < 1.1f)
        {
            //attack
            animator.SetTrigger("Attack");
            playerTran.SendMessage("TakeDamage",lossFood);
        }
        else
        {
            if (Mathf.Abs(offset.x) > Mathf.Abs(offset.y))
            {
                x = offset.x > 0 ? -1 : 1;
            }
            else
            {
                y = offset.y > 0 ? -1 : 1;
            }
            targetPos += new Vector2(x, y);
        }
        collider.enabled = false;
        RaycastHit2D hit = Physics2D.Linecast(targetPos, targetPos + new Vector2(x, y));
        collider.enabled = true;
        if (hit.transform == null)
        {
            rd2D.DOMove(targetPos, 0.3f);
        }
        else
        {
            targetPos -= new Vector2(x, y);
        }
      
    }

    

}